package com.tqz.zookeeper.lock;

import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * 使用zookeepr实现的分布式锁测试.
 *
 * @author <a href="https://github.com/tian-qingzhao">tianqingzhao</a>
 * @since 2025/9/6 12:02
 */
@Slf4j
public class DistributedLockTest implements Runnable {

    private static int count = 0;

    private final Lock lock = new DistributedLockByEphemeral();

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(30);

        for (int i = 0; i < 30; i++) {
            new Thread(new DistributedLockTest()).start();

            countDownLatch.countDown();
        }

        countDownLatch.await();
    }

    @Override
    public void run() {
        lock.lock();
        try {
            String orderCode = getOrderCode();
            log.info("生成订单号 {}", orderCode);
        } finally {
            lock.unlock();
        }
    }

    public String getOrderCode() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        return simpleDateFormat.format(new Date()) + "-" + ++count;
    }

}
